﻿<style>

    .haoyousq {
        position: absolute;
        right: 100%;
        top: 100%;
        background-color: rgb(17,17,17);
        display: flex;
        flex-direction: column;
        width: 100%;
        height: 100%;
    }

        .haoyousq .haoyousq-header {
            width: 100%;
            padding: 15px 0 15px 10px;
            color: #fff;
        }

        .haoyousq .sq-list-container {
            width: 100%;
            display: flex;
            justify-content: center;
            color: #fff;
        }

    .sq-list-container .sq-list {
        width: 500px;
    }

    .sq-list-item {
        border-radius: 10px;
        background-color: rgb(38,38,38);
        padding: 15px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
    }

        .sq-list-item img {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            object-fit: cover;
            margin-right: 8px;
        }

    .sq-list-item-main .item-top {
        color: #fff;
        font-size: 15px;
    }

        .sq-list-item-main .item-top .name {
            color: rgb(0,153,255);
            margin-right: 6px;
        }

    .sq-list-item .item-bottom {
        color: #ccc;
    }

        .sq-list-item .item-bottom .text {
            width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            font-size: 14px;
            color: #ccc;
        }

    .bl1-container {
        position: relative;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        color: #fff
    }

    .like-animation {
        color: #fff;
        position: absolute;
        opacity: 0;
    }

    .an {
        animation: likeAnimation 0.8s linear forwards;
    }

    .hxd-1 {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 400px;
        padding-bottom: 20px;
        border-bottom: 1px solid rgba(97,97,97,.3)
    }

    .box2 {
        background-color: rgb(51,51,51);
        color: #ccc;
        line-height: 40px;
        padding: 0 14px;
        border: 1px #ccc solid;
        border-radius: 5px;
        text-indent: 1em;
        margin: 15px 0;
    }

        .box2 input:focus {
            outline: none;
        }

    .box2_input1 {
        width: 320px;
        color: white;
        border: none;
        background-color: rgb(51,51,51);
        height: 22px;
        font-size: 15px;
        margin: 0 0 0 20px;
    }

    .preserve:hover, .cancel:hover {
        background-color: rgb(20,114,208);
    }

    .upload-container {
        color: #fff;
        font-family: Arial, sans-serif;
        position: relative;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }

    input[type="file"] {
        display: none;
    }

    .upload-pic {
        position: absolute;
        display: none;
        width: 81px;
        height: 81px;
        border-radius: 50%;
        object-fit: cover;
    }

    .upload-btn {
        width: 80px;
        height: 80px;
        border-radius: 50%;
        border: 1px dotted #fff;
    }

    .ckl {
        width: 220px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-size: 14px;
        color: rgb(97,97,97);
    }

    .fail {
        position: absolute;
        top: 0;
        left: 50%;
        transform: translateX(-50%);
        z-index: 999999999999;
        height: 80px;
        overflow: hidden;
    }
</style>

<div class="alert fail" id="liveAlertPlaceholder"></div>
<div class="container-fluid">
    <div class="row main">
        <div class="col-1 left-nav">
            <div class="avatar">
                <img src="~/image/default.jpg" />
            </div>
            <ul class="nav flex-column">
                <li class="nav-item" data-index="" onclick="window.location = '/chat'">
                    <i class="bi bi-chat-dots"></i>
                </li>
                <li class="nav-item active" onclick="window.location = '/chat/contact'">
                    <i class="bi bi-person"></i>
                </li>
                <li class="nav-item" data-bs-toggle="modal" data-bs-target="#exampleModal2">
                    <i class="bi bi-gear"></i>
                </li>
            </ul>
        </div>

        <div class="col-3 f-list">
            <div class="f-list-top">
                <div class="f-tongzhi" data-bs-toggle="modal" data-bs-target="#exampleModal1">
                    去添加好友
                    <i class="bi bi-plus-lg"></i>
                </div>
            </div>
            <div class="f-list-col">

            </div>
        </div>
        <div class="col-8 chat-main">
            <img class="pic-qq" src="~/image/nochat-bg.png" />
            <div class="content">

            </div>

        </div>

    </div>

</div>

<div class="modal fade" id="exampleModal1" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content" style="background-color:rgb(27,27,27)">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="exampleModalLabel" style="color:#fff">添加好友</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="input-group mb-3" style="align-items:center!important">
                    <span class="input-group-text" style="height:50px;">
                        <i class="bi bi-search"></i>
                    </span>
                    <input type="text" style="height:50px;" class="form-control search-ipt" placeholder="用户账号/手机号" aria-label="Recipient's username" aria-describedby="button-addon2">
                    <button class="btn btn-outline-secondary" type="button" id="button-addon2" style="height:50px;">搜索</button>
                </div>
                <div class="empty-search" style="margin-top:80px;display:flex;flex-direction:column;justify-content:center;align-items:center">
                    <div>
                        <div class="icon-container" style=" color:#fff; width: 60px; height: 60px; border: 3px solid #fff; border-radius: 50%; display: flex; justify-content: center; align-items: center; font-size: 18px;">
                            <i class="bi bi-person-lines-fill"></i>
                        </div>
                    </div>
                    <p style="color:#fff;margin-top:12px">快来发现更多好友</p>
                </div>
                <div class="search-result" style="display:none">

                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="exampleModal2" tabindex="-1" aria-labelledby="exampleModalLabe2" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content" style="background-color:rgb(27,27,27)">
            <div class="modal-header">
                <h1 class="modal-title fs-5" style="color:#fff" id="exampleModalLabel">个人资料</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form class="modal-body">
                <div class="upload-container">
                    <label for="hxd" class="upload-btn"></label>
                    <input id="hxd" class="upload" type="file" accept="image/*" />
                    <img class="upload-pic" />
                </div>
                <div class="box2">昵称<input tupe="text" class="box2_input1 nc" /></div>
                <div class="box2">年龄<input tupe="text" class="box2_input1 age" /></div>
                <div class="box2">签名<input tupe="text" class="box2_input1 qm" /></div>
                <div class="box2">密码<input tupe="text" class="box2_input1 pwd" /></div>
                <div style="display:flex;justify-content:flex-end">
                    <button style="margin-left:15px;" type="button" class="btn btn-outline-secondary sumbit">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>
<script src="~/Scripts/jquery-3.7.1.js"></script>
<script src="~/Scripts/jquery.signalR-2.4.3.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.-->
<script>

        var chat = $.connection.chatHub;

        chat.client.close = function () {
            alert("close");
            $.connection.hub.stop();
        };

        chat.client.refresh = function () {
            setTimeout(() => {
                getUser()
            }, 100);

        };


        $.connection.hub.start().done(function () {
            $('.ipt').keydown(function (event) {
                if (event.which === 13) {
                    SendAction();
                    setTimeout(() => {
                        $('.ipt').val('')
                    })
                }
            })
            console.log(11111111)
            chat.server.auth(localStorage.getItem("token"));
        });



    // This optional function html-encodes messages for display in the page.
    function fun(value) {
        alert(value);
    }

    const alertPlaceholder = document.getElementById('liveAlertPlaceholder')
    const Alert = (message, type) => {
        const wrapper = document.createElement('div')
        wrapper.innerHTML = [
            `<div class="alert alert-${type} alert-dismissible" role="alert">`,
            `   <div style="margin-right:40px;">${message}</div>`,
            '   <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>',
            '</div>'
        ].join('')

        alertPlaceholder.append(wrapper)

        setTimeout(() => {
            wrapper.remove()
        }, 2000)
    }

    @* 是否登陆 *@
    function isLogin() {
        fetch('/api/auth', {
            method: "post",
            headers: {
                'token': localStorage.getItem("token")
            }
        }).then((data) => {
            if (data.status == 401) {
                window.location.href = '/chat/login'
            }
        })
    }
    isLogin()

    function YMD(milliseconds) {
        milliseconds = +milliseconds
        // 创建一个新的Date对象，使用传入的毫秒数
        var date = new Date(milliseconds);

        // 获取年份、月份、日期、小时和分钟
        var year = date.getFullYear();
        var month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以需要+1
        var day = String(date.getDate()).padStart(2, '0');
        var hours = String(date.getHours()).padStart(2, '0');
        var minutes = String(date.getMinutes()).padStart(2, '0');

        console.log(date, year)

        // 构造并返回格式化的日期字符串
        return `${year}年${month}月${day}日 ${hours}:${minutes}`;
    }

    function extractNumbers(str) {
        let matches = str.match(/\d+/g);
        return matches ? matches.join("") : "";
    }

    var u_data;
    const icon = document.querySelector(".bl1-container")
    function addLike(l) {
        console.log("执行了")
        const num = document.querySelector(".num")
        const likeAnimation = document.querySelector('.like-animation');

        // 创建动画元素的副本
        const clone = likeAnimation.cloneNode(true);

        const randomColor = getRandomColor();
        clone.style.color = randomColor;

        clone.classList.add("an")
        num.innerText = parseInt(num.innerText) + 1


        const giveLikeData = new FormData()
        giveLikeData.append('uid',l)
        fetch('/api/giveLike', {
                headers: {
                    'token': localStorage.getItem("token")
                },
            method:'post',
            body: giveLikeData
        })


        // 将副本添加到页面中
        likeAnimation.parentNode.appendChild(clone);

        // 移除副本，防止页面占用过多内存
        clone.addEventListener('animationend', () => {
            clone.remove();
        });
    }
    function getRandomColor() {
        const letters = '0123456789ABCDEF';
        let color = '#';
        for (let i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }

    const upload = document.querySelector(".upload")
    const upload_pic = document.querySelector(".upload-pic")
    const upload_btn = document.querySelector(".upload-btn")
    upload_pic.addEventListener('click', () => {
        upload_btn.click()
    })

    upload.addEventListener('change', up);
    function up() {
        var file = this.files[0];
        if (file) {
            var reader = new FileReader();
            reader.onload = function (e) {
                upload_pic.setAttribute("src", e.target.result)
                upload_pic.style.display = 'block'
            }
            reader.readAsDataURL(file);
            console.log(file)

            var formData = new FormData();
            formData.append("imageFile", file);

            fetch("/api/UploadFile", {
                method: "POST",
                headers: {
                    'token': localStorage.getItem("token")
                },
                body: formData
            })
                .then(response => response.json())
                .then(data => {
                    if (data.Code === 200) {
                        u_data.AvatarImageURL = data.FileNmae
                    } else {
                        alert("图片上传失败")
                    }
                })
                .catch(error => {
                    alert("图片上传错误")
                });

        }
    }

    const nc = document.querySelector(".nc")
    const age = document.querySelector(".age")
    const qm = document.querySelector(".qm")
    const pwd = document.querySelector(".pwd")
    const sumbit = document.querySelector(".sumbit")

    sumbit.addEventListener('click', () => {
        const formdata = new FormData()

        formdata.append('UserName', nc.value)
        formdata.append('Age', age.value)
        formdata.append('PersonalSignature', qm.value)
        formdata.append('Password', pwd.value)
        formdata.append('AvatarImageURL', u_data.AvatarImageURL)

        fetch("/api/updateUserByUserId", {
            method: "POST",
            headers: {
                'token': localStorage.getItem("token")
            },
            body: formdata
        })
            .then(response => response.json())
            .then(data => {
                if (data.Code === 200) {
                    getUser()
                    Alert("修改成功！", 'success')


                } else {
                    Alert("什么也没有发生", 'danger')
                }
            })
            .catch(error => {
                alert("error", 'error')
            });


    })

    var u_data
    const avatar = document.querySelector(".avatar img")
    const f_list = document.querySelector(".f-list-col")
    function getUser() {
        fetch("/api/getFriendAndLastMessage", {
            method: "post",
            headers: {
                'token': localStorage.getItem("token")
            }
        }).then((data) => data.json())
            .then((data) => {

                u_data = data.User;
                @*
                    更改用户头像
                    *@
                    avatar.setAttribute("src", data.User.AvatarImageURL)
                f_list.innerHTML = ''
                for (let item of data.FriendsAndLastMessage) {
                    f_list.innerHTML += `
                    <div class="f-list-contact" data-UserID=${item.friend.UserID}  onclick="paint(this)">
                    <div class="pic">
                        <img src="${item.friend.AvatarImageURL}" />
                    </div>
                    <div class="contact-info">
                        <div class="info-top">${item.friend.UserName}</div>
                        <div class="info-online">[个性签名] ${item.friend.PersonalSignature == null ? '这个人很高冷，什么也没有留下' : item.friend.PersonalSignature}</div>
                    </div>
                </div>
`
                }

                nc.value = u_data.UserName
                age.value = u_data.Age
                qm.value = u_data.PersonalSignature
                upload_pic.setAttribute("src", u_data.AvatarImageURL)
                upload_pic.style.display = 'block'
            })
    }
    getUser()

    function reflow(id) {
        const content_main = document.querySelector(".chat-main .content")
        var getUserByUserIdFromData = new FormData();
        getUserByUserIdFromData.append('userId', id);

        @* 获取好友信息 *@
        fetch("/api/getUserByUserId", {
            method: "post",
            headers: {
                'token': localStorage.getItem("token")
            },
            body: getUserByUserIdFromData
        }).then(data => data.json())
            .then(data => {
                f_data = data.User
                const male = 'bi-gender-male'
                const fmale = 'bi-gender-female'

                    content_main.innerHTML = `
                        <div style="margin:0 auto;margin-top:150px">
                    <div class="hxd-1">
                        <div style="display:flex;align-items:flex-end">
                            <img src="${f_data.AvatarImageURL}" style=" width: 80px; height: 80px; border-radius: 50%; object-fit: cover;" />
                            <div style="margin-left:10px;">
                                <div style="font-size: 18px;color:#fff;">${f_data.UserName}</div>
                                <div class="ckl">Tel ${f_data.PhoneNumber}</div>
                            </div>
                        </div>
                        <div>
                            <div class="bl1-container" onclick='addLike(${f_data.UserID})'>
                                    <i class="bi bi-hand-thumbs-up bl1" style="margin-bottom:2px;"></i>
                                    <span class="num">${f_data.LikesCount}</span>
                                    <i class="bi bi-hand-thumbs-up like-animation" style="margin-bottom:2px;"></i>
                            </div>
                        </div>
                    </div>
                </div>
                                    <div style="margin:0 auto;margin-top:15px;width:400px">
                    <div style="color:#fff;display:flex;justify-content:space-around;width:200px">
                        <div>
                            <i class="bi ${f_data.Gender == null ? male : fmale}" style="color:blue"></i>
                            ${f_data.Gender == null ? '未知' : f_data.Gender}
                        </div>
                        <div style="width:2px;height:24px;background-color:rgba(255,255,255,0.1);"></div>
                        <div style="margin: 0 10px;">
                            ${f_data.Age == null ? 0 : f_data.Age}岁
                        </div>
                        <div style="width:2px;height:24px;background-color:rgba(255,255,255,0.1);"></div>
                        <div>
                            9月10日
                        </div>
                    </div>

                    <div style="display:flex;justify-content:space-between;align-items:center;color:#fff;margin-top:15px;">
                        <div>
                            <i class="bi bi-pencil-square"></i>
                            签名
                        </div>
                        <div>
                            ${f_data.PersonalSignature == null ? '这个人很高冷，什么也没有留下' : f_data.PersonalSignature}
                        </div>
                    </div>

                    <div style="display:flex;justify-content:flex-end;align-items:center;margin-top:25px;">
                        <button class="btn btn-primary" onclick="window.location.href='/chat?f_id=${f_data.UserID}'">发消息</button>
                    </div>
                </div>
                    `

            })
    }

    function paint(s) {
        var qq_bg = document.querySelector(".chat-main .pic-qq")
        const content = document.querySelector(".chat-main .content")
        var f_items = document.getElementsByClassName("f-list-contact")
            for (let i = 0; i < f_items.length; i++) {
                f_items[i].classList.remove('active')
            }
            s.classList.add('active')
            qq_bg.style.display = 'none'
            content.style.left = 0
        content.style.top = 0

        reflow(parseInt(s.getAttribute('data-UserID')))
    }

    document.querySelector('#button-addon2').addEventListener('click', () => {
        const msg = document.querySelector(".search-ipt").value.trim()

        var formData = new FormData();

        const op = document.querySelector('.search-result')

        formData.append('phoneNumber',msg)
        fetch('/api/getUserByPhoneNumber', {
            method: 'post',
            headers: {
                'token': localStorage.getItem('token')
            },
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                if (data.Code == 201) {
                    document.querySelector('.empty-search p').innerText = '未找到该用户'
                    document.querySelector('.empty-search').style.display = 'flex'
                    op.style.display = 'none'
                } else {

                    op.innerHTML = `
                    <div style="font-size:14px;color:#ccc;">查找人</div>
                        <div style="display:flex;justify-content:space-between;align-items:center;margin-top:10px;">
                                <div style="display:flex">
                                    <img class="pic-qq" src="${data.User.AvatarImageURL}" style=" width: 40px; height: 40px; border-radius: 50%; object-fit: cover;" />
                                    <div style="margin-left:10px;">
                                         <div style="color: #ccc">${data.User.UserName}</div>
                                    <div style="font-size: 14px; color: #ccc;color:blue">${data.User.PhoneNumber}</div>
                                </div>
                        </div>
                    <div>
                            <button class="btn btn-secondary add-friend" style="color:#fff">添加</button>
                        </div>
                    </div>

`

                    document.querySelector(".add-friend").addEventListener('click', () => {
                        var formData = new FormData();
                        formData.append("FriendId", data.User.UserID)

                        fetch('/api/addFriend', {
                            method: 'post',
                            headers: {
                                'token': localStorage.getItem('token') // 替换为你的身份验证令牌
                            },
                            body: formData
                        })
                            .then(response => response.json())
                            .then(data => {
                                Alert(data.Meg, `${data.Code == 210 ? 'danger' : 'success'}`)
                                if (data.Code == 200) {
                                    chat.server.refreshFriend(formData.get("FriendId"));
                                }
                            })
                            .catch(error => {
                                console.error(error);
                            });
                    })

                    document.querySelector('.empty-search').style.display = 'none'
                    op.style.display = 'block'
                }
            })
    })
</script>